import { constantRoutes } from "@/router";
import { store } from "@/store";
import router from "@/router";

import MenuAPI from "@/api/system/menu.api";
const modules = import.meta.glob( "../../views/**/**.vue" );
const Layout = () => import( "@/layout/index.vue" );


export const usePermissionStore = defineStore( "permission", () => {
    // 储存所有路由，包括静态和动态
    const routes = ref( [] );
    // 混合模式左侧菜单路由
    const mixedLayoutLeftRoutes = ref( [] );

    const isRoutesLoaded = ref( false );

    function generateRoutes () {
        return new Promise( ( resolve, reject ) => {
            MenuAPI.getRoutes()
                .then( ( data ) => {
                    const dynamicRoutes =
                        parseDynamicRoutes( data );
                    routes.value = [...constantRoutes, ...dynamicRoutes];
                    isRoutesLoaded.value = true;
                    resolve( dynamicRoutes );
                } )
                .catch( ( error ) => {
                    reject( error );
                } );
        } );
    }

    /**
 * 根据父菜单路径设置混合模式左侧菜单
 *
 * @param parentPath 父菜单的路径，用于查找对应的菜单项
 */
    const setMixedLayoutLeftRoutes = ( parentPath ) => {
        const matchedItem = routes.value.find( ( item ) => item.path === parentPath );
        if ( matchedItem && matchedItem.children ) {
            mixedLayoutLeftRoutes.value = matchedItem.children;
        }
    };

    // 重置路由
    const resetRouter = () => {
        // 从router实例中移除动态路由
        routes.value.forEach( ( route ) => {
            if ( route.name && !constantRoutes.find( ( r ) =>
                r.name === route.name ) ) {
                router.removeRoute( route.name );
            }
        } );

        // 清空本地存储的路由和菜单数据
        routes.value = [];
        mixedLayoutLeftRoutes.value = [];
        isRoutesLoaded.value = false;

        return {
            routes,
            mixedLayoutLeftRoutes,
            isRoutesLoaded,
            generateRoutes,
            setMixedLayoutLeftRoutes,
            resetRouter,
        };
    };


} );

// 解析后端返回的路由数据
const parseDynamicRoutes = ( rawRoutes ) => {
    const parsedRoutes = [];

    rawRoutes.forEach( ( route ) => {
        const normalizedRoute = { ...route };

        // 处理组件路径
        normalizedRoute.component =
            normalizedRoute.component?.toString() === "Layout" ? Layout : modules[`../../views/${normalizedRoute.component}.vue`] || modules["../../views/error-page/404.vue"];

        // 递归解析子路由
        if ( normalizedRoute.children ) {
            normalizedRoute.children = parseDynamicRoutes( route.children );
        }

        parsedRoutes.push( normalizedRoute );
    } );
};

export function usePermissionStoreHook () {
    return usePermissionStore( store );
}